<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/%E5%8D%9A%E5%AE%A2.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/%E5%8D%9A%E5%AE%A2.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/%E5%8D%9A%E5%AE%A2.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="java,java集合容器," />





  <link rel="alternate" href="/atom.xml" title="Createsequence's Blog" type="application/atom+xml" />






<meta name="description" content="概述 List 应该接口是 Collection 最常被使用的接口了。其下的实现类皆为有序列表，其中主要分为 Vector，ArrayList，LinkedList 三个实现类，其中 Vecotr 又拥有子类 Stack。 从线程安全来说，List 下拥有线程安全的集合类 Vector；从数据结构来说，List 下拥有基于数组实现的 Vector 与 ArrayList，和基于链表实现的 Li">
<meta property="og:type" content="article">
<meta property="og:title" content="java集合源码分析（二）：List与AbstractList">
<meta property="og:url" content="http://blog.xiajibagao.top/2020/11/27/java/%E9%9B%86%E5%90%88%E7%B1%BB%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/java%E9%9B%86%E5%90%88%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90%EF%BC%88%E4%BA%8C%EF%BC%89%EF%BC%9AList%E4%B8%8EAbstractList/index.html">
<meta property="og:site_name" content="Createsequence&#39;s Blog">
<meta property="og:description" content="概述 List 应该接口是 Collection 最常被使用的接口了。其下的实现类皆为有序列表，其中主要分为 Vector，ArrayList，LinkedList 三个实现类，其中 Vecotr 又拥有子类 Stack。 从线程安全来说，List 下拥有线程安全的集合类 Vector；从数据结构来说，List 下拥有基于数组实现的 Vector 与 ArrayList，和基于链表实现的 Li">
<meta property="og:locale">
<meta property="og:image" content="http://img.xiajibagao.top/image-20201125163518482.png">
<meta property="og:image" content="http://img.xiajibagao.top/image-20201126114026855.png">
<meta property="og:image" content="http://img.xiajibagao.top/image-20201126204925206.png">
<meta property="og:image" content="http://img.xiajibagao.top/image-20201126110250536.png">
<meta property="article:published_time" content="2020-11-26T16:00:00.000Z">
<meta property="article:modified_time" content="2020-12-22T08:12:09.108Z">
<meta property="article:author" content="Createsequence">
<meta property="article:tag" content="java">
<meta property="article:tag" content="java集合容器">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://img.xiajibagao.top/image-20201125163518482.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.xiajibagao.top/2020/11/27/java/集合类源码分析/java集合源码分析（二）：List与AbstractList/"/>





  <title>java集合源码分析（二）：List与AbstractList | Createsequence's Blog</title>
  








<meta name="generator" content="Hexo 5.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Createsequence's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">一个努力前进的程序猿</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.xiajibagao.top/2020/11/27/java/%E9%9B%86%E5%90%88%E7%B1%BB%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/java%E9%9B%86%E5%90%88%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90%EF%BC%88%E4%BA%8C%EF%BC%89%EF%BC%9AList%E4%B8%8EAbstractList/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/Createsequence.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Createsequence's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">java集合源码分析（二）：List与AbstractList</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-11-27T00:00:00+08:00">
                2020-11-27
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/java%E9%9B%86%E5%90%88%E5%AE%B9%E5%99%A8/" itemprop="url" rel="index">
                    <span itemprop="name">java集合容器</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  5.9k
                </span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="概述">概述</h2>
<p>List 应该接口是 Collection 最常被使用的接口了。其下的实现类皆为有序列表，其中主要分为 Vector，ArrayList，LinkedList 三个实现类，其中 Vecotr 又拥有子类 Stack。</p>
<p>从线程安全来说，List 下拥有线程安全的集合类 Vector；从数据结构来说，List 下拥有基于数组实现的 Vector 与 ArrayList，和基于链表实现的 LinkedList。</p>
<p>本篇文章暂不讨论具体的实现类，而将基于 List 接口与其抽象类 AbstractList，了解 List 接口是如何承上启下，进一步从 Collection 抽象到具体的。</p>
<blockquote>
<p>这是关于 java 集合类源码的第二篇文章。往期文章：</p>
<p><a href="https://blog.xiajibagao.top/2020/11/25/java/集合类源码分析/java集合源码分析（一）：Collection与AbstractCollection/">java集合源码分析（一）：Collection 与 AbstractCollection</a></p>
</blockquote>
<h2 id="一-list-接口">一、List 接口</h2>
<figure>
<img src="http://img.xiajibagao.top/image-20201125163518482.png" alt="List 接口的方法"><figcaption aria-hidden="true">List 接口的方法</figcaption>
</figure>
<p>List 接口继承了 Collection 接口，在 Collection 接口的基础上增加了一些方法。相对于 Collection 接口，我们可以很明显的看到，List <strong>中增加了非常多根据下标操作集合的方法</strong>，我们可以简单粗暴的分辨一个方法的抽象方法到底来自 Collection 还是 List：参数里有下标就是来自 List，没有就是来自 Collection。</p>
<p>可以说，List 接口在 Collection 的基础上，<strong>进一步明确了 List 集合运允许根据下标快速存取的特性</strong>。</p>
<h3 id="1新增的方法">1.新增的方法</h3>
<ul>
<li><code>get()</code>：根据下标获取指定元素；</li>
<li><code>replaceAll()</code>：参数一个函数式接口<code>UnaryOperator&lt;E&gt;</code>，这个方法允许我们通过传入的匿名实现类的方法去对集合中的每一个类做一些处理以后再放回去；</li>
<li><code>sort()</code>：对集合中的数据进行排序。参数是 <code>Comparator&lt;? super E&gt;</code>，这个参数让我们传入一个比较的匿名方法，用于数组排序；</li>
<li><code>set()</code>：用指定的元素替换集合中指定位置的元素；</li>
<li><code>indexOf()</code>：返回指定元素在此列表中首次出现的索引；如果此列表不包含该元素，则返回-1；</li>
<li><code>lastIndexOf()</code>：返回指定元素在此列表中最后一次出现的索引，否则返回-1；</li>
<li><code>listIterator()</code>：这个是个多态的方法。无参的 <code>listIterator()</code>用于获取迭代器，而有参的 <code>listIterator()</code>可以传入下标，从集合的指定位置开始获取迭代器。指定的索引指示首次调用next将返回的第一个元素。</li>
<li><code>subList()</code>：返回此列表中指定的两个指定下标之间的集合的视图。注意，这里说的<strong>是视图，因而对视图的操作会影响到集合，反之亦然。</strong></li>
</ul>
<h3 id="2同名的新方法">2.同名的新方法</h3>
<ul>
<li><code>add()</code>：添加元素。List 中的 <code>add()</code> 参数的（int，E），而 Collection 中的 <code>add()</code> 参数是 E，<strong>因此 List 集合中同时存在指定下标和不指定下标两种添加方式</strong>；</li>
<li><code>remove()</code>：删除指定下标的元素。注意，List 的 <code>remove()</code> 参数是 int ，而 Collection 中的 `<code>remove()</code> 参数是 Objce，也就是说，<strong>List 中同时存在根据元素是否相等和根据元素下标删除元素两种方式</strong>。</li>
</ul>
<h3 id="3重写的方法">3.重写的方法</h3>
<ul>
<li><code>spliterator()</code>：List 接口重写了 Collection 接口的默认实现，换成了根据顺序的分割。</li>
</ul>
<h2 id="二-abstractlist-抽象类">二、AbstractList 抽象类</h2>
<p>AbstractList 类是一个继承了 AbstractCollection 类并且实现了 List 接口的抽象类，它相当于在 AbstractCollection 后的第二层方法模板。是对 List 接口的初步实现，同时也是 Collection 的进一步实现。</p>
<p>我们可以根据 JavaDoc 简单的了解一下它：</p>
<blockquote>
<p>此类提供List接口的基本实现，以最大程度地减少实现由“随机访问”数据存储（例如数组）支持的此接口所需的工作。 对于顺序访问数据（例如链表），应优先使用AbstractSequentialList代替此类。</p>
<p><strong>要实现不可修改的列表</strong>，程序员只需要扩展此类并为get(int)和size()方法提供实现即可。</p>
<p><strong>要实现可修改的列表</strong>，程序员必须另外重写set(int, E)方法（否则将抛出UnsupportedOperationException ）。 如果列表是可变大小的，则程序员必须另外重写add(int, E)和remove(int)方法。</p>
<p>不像其他的抽象集合实现，程序员<strong>不必提供迭代器实现</strong>;</p>
<p><strong>迭代器和列表迭代器由此类在“随机访问”方法之上实现</strong>： get(int) ， set(int, E) ， add(int, E)和remove(int) 。</p>
</blockquote>
<h3 id="1不支持的实现与抽象方法">1.不支持的实现与抽象方法</h3>
<p>可以直接通过下标操作的<code>set()</code>，<code>add()</code>，<code>remove()</code>都是 List 引入的新接口，这些都 AbstractList 都不支持，要使用必须由子类重写。</p>
<p><code>get()</code>由于不能确定子类是链表还是数组，所以此时<code>get()</code>仍然强制要求子类去实现。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">abstract</span> <span class="keyword">public</span> E <span class="title">get</span><span class="params">(<span class="keyword">int</span> index)</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> E <span class="title">set</span><span class="params">(<span class="keyword">int</span> index, E element)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> UnsupportedOperationException();</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">add</span><span class="params">(<span class="keyword">int</span> index, E element)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> UnsupportedOperationException();</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">public</span> E <span class="title">remove</span><span class="params">(<span class="keyword">int</span> index)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> UnsupportedOperationException();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="2内部类们">2.内部类们</h3>
<p>跟 AbstractCollection 类不同，AbstractList 拥有几个特别的内部类，他们分别的迭代器类：Itr 和 ListItr，对应获取他们的方法是：</p>
<ul>
<li><code>iterator()</code>：获取 Itr 迭代器类；</li>
<li><code>listIterator()</code>：获取 ListItr 迭代器类。这是个多态方法，可以选择是否从指定下标开始，默认从下标为0的元素开始迭代；</li>
</ul>
<p>视图类 SubList 和 RandomAccessSubList：</p>
<ul>
<li><code>subList()</code>：获取视图类，会自动根据实现类是否继承 RandomAccess 而返回 SubList 或 RandomAccessSubList。</li>
</ul>
<p>这些内部类同样被一些其他的方法所依赖，所以要全面的了解 AbstractList 方法的实现，就需要先了解这些内部类的作用和实现原理。</p>
<h2 id="三-sublist方法与内部类">三、subList方法与内部类</h2>
<p><code>subList()</code>算是一个比较常用的方法了，在 List 接口的规定中，这个方法应该返回一个当前集合的一部分的视图：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> List&lt;E&gt; <span class="title">subList</span><span class="params">(<span class="keyword">int</span> fromIndex, <span class="keyword">int</span> toIndex)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 是否是实现了RandomAccess接口的类</span></span><br><span class="line">    <span class="keyword">return</span> (<span class="keyword">this</span> <span class="keyword">instanceof</span> RandomAccess ?</span><br><span class="line">            <span class="comment">// 是就返回一个可以随机访问的内部类RandomAccessSubList</span></span><br><span class="line">            <span class="keyword">new</span> RandomAccessSubList&lt;&gt;(<span class="keyword">this</span>, fromIndex, toIndex) :</span><br><span class="line">            <span class="comment">// 否则返回一个普通内部类SubList</span></span><br><span class="line">            <span class="keyword">new</span> SubList&lt;&gt;(<span class="keyword">this</span>, fromIndex, toIndex));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里涉及到 RandomAccessSubList 和 SubList 这个内部类，其中，RandomAccessSubList 类是 SubList 类的子类，但是实现了 RandomAccess 接口。</p>
<h3 id="1sublist-内部类">1.SubList 内部类</h3>
<p>我们可以简单的把 SubList 和 AbstractList 理解为装饰器模式的一种实现，就像 SynchronizedList 和 List 接口的实现类一样。SubList 内部类通过对 AbstractList 的方法进行了再一次的封装，把对 AbstractList 的操作转变为了对 “视图的操作”。</p>
<p>通过对原有的 AbstractList 进行包装，将原本对 AbstractList 操作的方法改为了对 SubList 的操作的方法，是适配器模式思想的一种体现。</p>
<p>我们先看看 SubList 这个类的成员变量和构造方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">SubList</span>&lt;<span class="title">E</span>&gt; <span class="keyword">extends</span> <span class="title">AbstractList</span>&lt;<span class="title">E</span>&gt; </span>&#123;</span><br><span class="line">    <span class="comment">// 把外部类AbstractList作为成员变量</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> AbstractList&lt;E&gt; l;</span><br><span class="line">    <span class="comment">// 表示视图的起始位置（偏移量）</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> offset;</span><br><span class="line">    <span class="comment">// SubList视图的长度</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> size;</span><br><span class="line"></span><br><span class="line">    SubList(AbstractList&lt;E&gt; list, <span class="keyword">int</span> fromIndex, <span class="keyword">int</span> toIndex) &#123;</span><br><span class="line">        <span class="keyword">if</span> (fromIndex &lt; <span class="number">0</span>)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IndexOutOfBoundsException(<span class="string">&quot;fromIndex = &quot;</span> + fromIndex);</span><br><span class="line">        <span class="keyword">if</span> (toIndex &gt; list.size())</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IndexOutOfBoundsException(<span class="string">&quot;toIndex = &quot;</span> + toIndex);</span><br><span class="line">        <span class="keyword">if</span> (fromIndex &gt; toIndex)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;fromIndex(&quot;</span> + fromIndex +</span><br><span class="line">                                               <span class="string">&quot;) &gt; toIndex(&quot;</span> + toIndex + <span class="string">&quot;)&quot;</span>);</span><br><span class="line">        <span class="comment">// 获取外部类的引用</span></span><br><span class="line">        <span class="comment">// 这也是为什么操作视图或者外部类都会影响对方的原因，因为都操作内存中的同一个实例</span></span><br><span class="line">        l = list;</span><br><span class="line">        <span class="comment">// 获取当前视图在外部类中的起始下标</span></span><br><span class="line">        offset = fromIndex;</span><br><span class="line">        <span class="comment">// 当前视图的长度就是外部类截取的视图长度</span></span><br><span class="line">        size = toIndex - fromIndex;</span><br><span class="line">        <span class="keyword">this</span>.modCount = l.modCount;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>我们可以参考图片理解一下：</p>
<figure>
<img src="http://img.xiajibagao.top/image-20201126114026855.png" alt="image-20201126114026855"><figcaption aria-hidden="true">image-20201126114026855</figcaption>
</figure>
<p>然后 subList 里面的方法就很好理解了：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> E <span class="title">set</span><span class="params">(<span class="keyword">int</span> index, E element)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 检查下标是否越界</span></span><br><span class="line">    rangeCheck(index);</span><br><span class="line">    <span class="comment">// 判断是存在并发修改</span></span><br><span class="line">    checkForComodification();</span><br><span class="line">    <span class="comment">// 把元素添加到偏移量+视图下标的位置</span></span><br><span class="line">    <span class="keyword">return</span> l.set(index+offset, element);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>其他方法都差不多，这里便不再多费笔墨了。</p>
<h3 id="2randomaccesssublist-内部类">2.RandomAccessSubList 内部类</h3>
<p>然后是 SubList 的子类 RandomAccessSubList：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">RandomAccessSubList</span>&lt;<span class="title">E</span>&gt; <span class="keyword">extends</span> <span class="title">SubList</span>&lt;<span class="title">E</span>&gt; <span class="keyword">implements</span> <span class="title">RandomAccess</span> </span>&#123;</span><br><span class="line">    RandomAccessSubList(AbstractList&lt;E&gt; list, <span class="keyword">int</span> fromIndex, <span class="keyword">int</span> toIndex) &#123;</span><br><span class="line">        <span class="keyword">super</span>(list, fromIndex, toIndex);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> List&lt;E&gt; <span class="title">subList</span><span class="params">(<span class="keyword">int</span> fromIndex, <span class="keyword">int</span> toIndex)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> RandomAccessSubList&lt;&gt;(<span class="keyword">this</span>, fromIndex, toIndex);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>我们可以看见，他实际上还是 SubList，但是实现了 RandomAccess 接口。关于这个接口，其实只是一个标记，实现了该接口的类可以实现快速随机访问（下标），通过 for 循环+下标取值会比用迭代器更快。</p>
<p>Vector 和 ArrayList 都实现了这个接口，而 LinkedList 没有。专门做此实现也是为了在实现类调用的 <code>subList()</code>方法时可以分辨这三者。</p>
<h2 id="四-iterator方法与内部类">四、iterator方法与内部类</h2>
<p>在 AbstractList 里面，为我们提供了 Itr 和 ListItr 两种迭代器。</p>
<p>迭代器是 AbstractList 中很重要的一块内容，他是对整个接口体系的顶层接口，也就是 Iterable 接口中的 <code>iterator()</code> 方法的实现，源码中的很多涉及遍历的方法，都离不开内部实现的迭代器类。</p>
<h3 id="1迭代器的-fast-fail-机制">1.迭代器的 fast-fail 机制</h3>
<p>我们知道，AbstractList 默认是不提供线程安全的保证的，但是为了尽可能的避免并发修改对迭代带来的影响，JDK 引入一种 fast-fail 的机制，即如果检测的发生并发修改，就立刻抛出异常，而不是让可能出错的参数被使用从而引发不可预知的错误。</p>
<p>对此，AbstractList 提供了一个成员变量 <code>modCount</code>，JavaDoc 是这么描述它的：</p>
<blockquote>
<p>已对该列表进行结构修改的次数。</p>
<p>结构修改是指更改列表大小或以其他方式干扰列表的方式，即正在进行的迭代可能会产生错误的结果。该字段由iterator和listIterator方法返回的迭代器和列表迭代器实现使用。如果此字段的值意外更改，则迭代器（或列表迭代器）将抛出ConcurrentModificationException，以响应下一个，移除，上一个，设置或添加操作。</p>
<p>面对迭代期间的并发修改，这提供了快速失败的行为，而不是不确定的行为。</p>
<p>子类对此字段的使用是可选的。如果子类希望提供快速失败的迭代器（和列表迭代器），则只需在其add（int，E）和remove（int）方法（以及任何其他覆盖该方法导致结构化的方法）中递增此字段即可）。</p>
<p>一次调用add（int，E）或remove（int）不得在此字段中添加不超过一个，否则迭代器（和列表迭代器）将抛出虚假的ConcurrentModificationExceptions。</p>
<p>如果实现不希望提供快速失败迭代器，则可以忽略此字段。</p>
</blockquote>
<p>这个时候我们再回去看看迭代器类 Itr 的一部分代码，可以看到：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="class"><span class="keyword">class</span> <span class="title">Itr</span> <span class="keyword">implements</span> <span class="title">Iterator</span>&lt;<span class="title">E</span>&gt; </span>&#123;</span><br><span class="line">    <span class="comment">// 迭代器认为后备列表应该具有的modCount值。如果违反了此期望，则迭代器已检测到并发修改。</span></span><br><span class="line">    <span class="keyword">int</span> expectedModCount = modCount;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 检查是否发生并发操作</span></span><br><span class="line">    <span class="function"><span class="keyword">final</span> <span class="keyword">void</span> <span class="title">checkForComodification</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (modCount != expectedModCount)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> ConcurrentModificationException();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>结合代码，我们就不难理解这个 fast-fail 机制是怎么实现的了：</p>
<p>AbstractList 提供了一个成员变量用于记录对集合结构性修改的次数，如果子类希望实现并发修改错误的检查，就需要结构性操作的方法里让<code>modCount</code>+1。这样。在获取迭代器以后，迭代器内部会获取当前的<code>modCount</code>赋值给<code>expectedModCount</code>。</p>
<p>当使用迭代器迭代的时候，每一次迭代都会检测<code>modCount</code>和<code>expectedModCount</code>是否相等。如果不相等，说明迭代器创建以后，集合结构被修改了，这个时候再去进行迭代可能会出现错误（比如少遍历一个，多遍历一个），因此检测到后会直接抛出 <code>ConcurrentModificationException</code>异常。</p>
<p>ListItr 继承了 Itr ，因此他们都有一样的 fast-fail机制。</p>
<p>值得一提的是，<strong>对于启用了 fast-fail 机制的实现类，只有使用迭代器才能边遍历边删除</strong>，原因也是因为并发修改检测：</p>
<h3 id="2itr-迭代器">2.Itr 迭代器</h3>
<p>现在，回到 Itr 的代码上：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="class"><span class="keyword">class</span> <span class="title">Itr</span> <span class="keyword">implements</span> <span class="title">Iterator</span>&lt;<span class="title">E</span>&gt; </span>&#123;</span><br><span class="line">    <span class="comment">// 后续调用next返回的元素索引</span></span><br><span class="line">    <span class="keyword">int</span> cursor = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 最近一次调用返回的元素的索引。如果通过调用remove删除了此元素，则重置为-1。</span></span><br><span class="line">    <span class="keyword">int</span> lastRet = -<span class="number">1</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 迭代器认为后备列表应该具有的modCount值。如果违反了此期望，则迭代器已检测到并发修改。</span></span><br><span class="line">    <span class="keyword">int</span> expectedModCount = modCount;</span><br><span class="line">	</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">hasNext</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> cursor != size();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> E <span class="title">next</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        checkForComodification();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">int</span> i = cursor;</span><br><span class="line">            E next = get(i);</span><br><span class="line">            lastRet = i;</span><br><span class="line">            cursor = i + <span class="number">1</span>;</span><br><span class="line">            <span class="keyword">return</span> next;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IndexOutOfBoundsException e) &#123;</span><br><span class="line">            checkForComodification();</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> NoSuchElementException();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">remove</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (lastRet &lt; <span class="number">0</span>)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException();</span><br><span class="line">        checkForComodification();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            AbstractList.<span class="keyword">this</span>.remove(lastRet);</span><br><span class="line">            <span class="keyword">if</span> (lastRet &lt; cursor)</span><br><span class="line">                cursor--;</span><br><span class="line">            lastRet = -<span class="number">1</span>;</span><br><span class="line">            expectedModCount = modCount;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IndexOutOfBoundsException e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> ConcurrentModificationException();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">	</span><br><span class="line">    <span class="function"><span class="keyword">final</span> <span class="keyword">void</span> <span class="title">checkForComodification</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (modCount != expectedModCount)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> ConcurrentModificationException();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>迭代方法</strong></p>
<p>除了并发修改检测外，迭代器迭代的方式也出乎意料。我们可以看看 <code>hasNext()</code>方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> E <span class="title">next</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 检验是否发生并发修改</span></span><br><span class="line">    checkForComodification();</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">int</span> i = cursor;</span><br><span class="line">        E next = get(i);</span><br><span class="line">        lastRet = i;</span><br><span class="line">        cursor = i + <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">return</span> next;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (IndexOutOfBoundsException e) &#123;</span><br><span class="line">        checkForComodification();</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> NoSuchElementException();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这个逻辑其实跟链表的遍历是一样的，只不过指针变成了数组的下标。以链表的方式去理解：</p>
<p>我们把循环里调用<code>next()</code>之后的节点叫做下一个节点，反正称为当前节点。假如现在有 a，b，c 三个元素：</p>
<ul>
<li>当初始化的时候，指向最后一次操作的的节点的指针 <code>lastRet=-1</code>，即当前节点不存在，当前游标 <code>cursor=0</code>，即指向下一个节点 a；</li>
<li>当开始迭代的时候，把游标的值赋给临时指针 i，然后通过游标获取并返回下一个节点 a，再把游标指向 a 的下一个节点 b，此时 <code>cursor=1</code>，<code>lastRet=-1</code>，<code>i=1</code>；</li>
<li>接着让<code>lastRet=i</code>，也就是当前指针指向新的当前节点 a，现在 lastRet=0<code>，</code>cursor=1`，完成了对第一个节点 a 的迭代；</li>
<li>重复上述过程，把节点中的每一个元素都处理完。</li>
</ul>
<p>现在我们知道了迭代的方式，<code>cursor</code>和 <code>lastRet</code> 的作用，也就不难理解 <code>remove()</code>方法了：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">remove</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (lastRet &lt; <span class="number">0</span>)</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException();</span><br><span class="line">    checkForComodification();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">// 调用删除方法</span></span><br><span class="line">        AbstractList.<span class="keyword">this</span>.remove(lastRet);</span><br><span class="line">        <span class="keyword">if</span> (lastRet &lt; cursor)</span><br><span class="line">		   <span class="comment">// 因为删除了当前第i个节点，所以i+1个节点就会变成第i个节点，</span></span><br><span class="line">            <span class="comment">// 调用next()以后cursor会+1，因此如果不让cursor-1,就会,next()以后跳过原本的第i+1个节点</span></span><br><span class="line">            <span class="comment">// 拿上面的例子来说，你要删除abc，但是在删除a以后会跳过b直接删除c</span></span><br><span class="line">            cursor--;</span><br><span class="line">        <span class="comment">// 最近一个操作的节点被删除了，故重置为-1</span></span><br><span class="line">        lastRet = -<span class="number">1</span>;</span><br><span class="line">        <span class="comment">// 因为调用了外部类的remove方法，所以会改变modCount值，迭代器里也要获取最新的modCount</span></span><br><span class="line">        expectedModCount = modCount;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (IndexOutOfBoundsException e) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> ConcurrentModificationException();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>至于<code>hasNext()</code>方法没啥好说的，如果 <code>cursor</code>已经跟集合的长度一样长了，说明就已经迭代到底了。</p>
<h3 id="2listitr-迭代器">2.ListItr 迭代器</h3>
<p>ListItr 继承了 Itr 类，并且实现了 ListIterator 接口。其中，ListIterator 接口又继承了 Iterator 接口。他们的类关系图是这样的：</p>
<figure>
<img src="http://img.xiajibagao.top/image-20201126204925206.png" alt="ListIterator 的类关系图"><figcaption aria-hidden="true">ListIterator 的类关系图</figcaption>
</figure>
<p>ListIterator 接口在 Iterator 接口的基础上，主要提供了六个新的抽象方法：</p>
<ul>
<li><code>hasPrevious()</code>：是否有前驱节点；</li>
<li><code>previous()</code>：向前迭代；</li>
<li><code>nextIndex()</code>：获取下一个元素的索引；</li>
<li><code>previousIndex()</code>：返回上一个元素的索引；</li>
<li><code>set()</code>：替换元素；</li>
<li><code>add()</code>：添加元素；</li>
</ul>
<p>可以看出来，实现了 ListIterator 的 ListItr 类要比 Itr 更加强大，不但可以向后迭代，还能向前迭代，还可以在迭代过程中更新或者添加节点。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="class"><span class="keyword">class</span> <span class="title">ListItr</span> <span class="keyword">extends</span> <span class="title">Itr</span> <span class="keyword">implements</span> <span class="title">ListIterator</span>&lt;<span class="title">E</span>&gt; </span>&#123;</span><br><span class="line">    <span class="comment">// 可以自己设置迭代的开始位置</span></span><br><span class="line">    ListItr(<span class="keyword">int</span> index) &#123;</span><br><span class="line">        cursor = index;</span><br><span class="line">    &#125;</span><br><span class="line">	</span><br><span class="line">    <span class="comment">// 下一节点是否就是第一个节点</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">hasPrevious</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> cursor != <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> E <span class="title">previous</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 检查并发修改</span></span><br><span class="line">        checkForComodification();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">// 让游标指向当前节点</span></span><br><span class="line">            <span class="keyword">int</span> i = cursor - <span class="number">1</span>;</span><br><span class="line">            <span class="comment">// 使用AbstractList的get方法获取当前节点</span></span><br><span class="line">            E previous = get(i);</span><br><span class="line">            lastRet = cursor = i;</span><br><span class="line">            <span class="keyword">return</span> previous;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IndexOutOfBoundsException e) &#123;</span><br><span class="line">            checkForComodification();</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> NoSuchElementException();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">	</span><br><span class="line">    <span class="comment">// 获取下一节点的下标</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">nextIndex</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> cursor;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 获取当前节点（下一个节点的上一个节点）的下标</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">previousIndex</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> cursor-<span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">set</span><span class="params">(E e)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (lastRet &lt; <span class="number">0</span>)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException();</span><br><span class="line">        checkForComodification();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            AbstractList.<span class="keyword">this</span>.set(lastRet, e);</span><br><span class="line">            expectedModCount = modCount;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IndexOutOfBoundsException ex) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> ConcurrentModificationException();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">add</span><span class="params">(E e)</span> </span>&#123;</span><br><span class="line">        checkForComodification();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">int</span> i = cursor;</span><br><span class="line">            <span class="comment">// 往下一个节点的位置添加新节点</span></span><br><span class="line">            AbstractList.<span class="keyword">this</span>.add(i, e);</span><br><span class="line">            lastRet = -<span class="number">1</span>;</span><br><span class="line">            cursor = i + <span class="number">1</span>;</span><br><span class="line">            expectedModCount = modCount;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IndexOutOfBoundsException ex) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> ConcurrentModificationException();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里比较不好理解的是下一节点还有当前节点这个概念，其实可以这么理解：<code>cursor</code>游标指定的必定是下一次 <code>next()</code>操作要得到的节点，因此<code>cursor</code>在操作前或者操作后指向的必定就是下一节点，因此相对下一节点，<code>cursor</code>其实就是当前节点，相对下一节点来说就是上一节点。</p>
<p>也就是说，假如现在有 a，b，c 三个元素，现在的 <code>cursor</code> 为2，也就是指向 b。调用 <code>next()</code>以后游标就会指向 c，而调用<code>previous()</code>以后游标又会指回 b。</p>
<p>至于<code>lastRet</code>这个成员变量只是用于记录最近一次操作的节点是哪个，跟方向性是无关。</p>
<h2 id="五-abstractlist-实现的方法">五、AbstractList 实现的方法</h2>
<h3 id="1add">1.add</h3>
<p>注意，现在现在 AbstractList 的 <code>add(int index, E e)</code>仍然还不被支持，<code>add(E e)</code>只是定义了通过 <code>add(int index, E e)</code>把元素添加到队尾的逻辑。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 不指定下标的add，默认逻辑为添加到队尾</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">add</span><span class="params">(E e)</span> </span>&#123;</span><br><span class="line">    add(size(), e);</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>关于 AbstractList 和 AbstractCollection 中 <code>add()</code>方法之间的关系是这样的：</p>
<figure>
<img src="http://img.xiajibagao.top/image-20201126110250536.png" alt="add方法的实现逻辑"><figcaption aria-hidden="true">add方法的实现逻辑</figcaption>
</figure>
<p>AbstractList 这里的 <code>add(E e)</code>就非常有模板方模式提到的“抽象类规定算法骨架”这个感觉了。AbstractCollection 接口提供了 <code>add(E e)</code>的初步实现（尽管只是抛异常），然后到了 AbstractList 中就完善了 <code>add(E e)</code>方法的逻辑——通过调用 <code>add(int index,E e)</code>方法把元素插到队尾，但是具体的 <code>add(int index,E e)</code>怎么实现再交给子类决定。</p>
<h3 id="2indexoflastindexof">2.indexOf/LastIndexOf</h3>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">indexOf</span><span class="params">(Object o)</span> </span>&#123;</span><br><span class="line">    ListIterator&lt;E&gt; it = listIterator();</span><br><span class="line">    <span class="keyword">if</span> (o==<span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">while</span> (it.hasNext())</span><br><span class="line">            <span class="keyword">if</span> (it.next()==<span class="keyword">null</span>)</span><br><span class="line">                <span class="keyword">return</span> it.previousIndex();</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">while</span> (it.hasNext())</span><br><span class="line">            <span class="keyword">if</span> (o.equals(it.next()))</span><br><span class="line">                <span class="keyword">return</span> it.previousIndex();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">lastIndexOf</span><span class="params">(Object o)</span> </span>&#123;</span><br><span class="line">    ListIterator&lt;E&gt; it = listIterator(size());</span><br><span class="line">    <span class="keyword">if</span> (o==<span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">while</span> (it.hasPrevious())</span><br><span class="line">            <span class="keyword">if</span> (it.previous()==<span class="keyword">null</span>)</span><br><span class="line">                <span class="keyword">return</span> it.nextIndex();</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">while</span> (it.hasPrevious())</span><br><span class="line">            <span class="keyword">if</span> (o.equals(it.previous()))</span><br><span class="line">                <span class="keyword">return</span> it.nextIndex();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="3addall">3.addAll</h3>
<p>这里的<code>addAll</code>来自于List 集合的 <code>addAll</code>。参数是需要合并的集合跟起始下标：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">addAll</span><span class="params">(<span class="keyword">int</span> index, Collection&lt;? extends E&gt; c)</span> </span>&#123;</span><br><span class="line">    rangeCheckForAdd(index);</span><br><span class="line">    <span class="keyword">boolean</span> modified = <span class="keyword">false</span>;</span><br><span class="line">    <span class="keyword">for</span> (E e : c) &#123;</span><br><span class="line">        add(index++, e);</span><br><span class="line">        modified = <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> modified;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里的 <code>rangeCheckForAdd()</code>方法是一个检查下标是否越界的方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">rangeCheckForAdd</span><span class="params">(<span class="keyword">int</span> index)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 不得小于0或者大于集合长度</span></span><br><span class="line">    <span class="keyword">if</span> (index &lt; <span class="number">0</span> || index &gt; size())</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IndexOutOfBoundsException(outOfBoundsMsg(index));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="4removerange">4.removeRange</h3>
<p>这个方法是 AbstractList 私有的方法，一般被子类用于删除一段多个元素，实现上借助了 ListIter 迭代器。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">removeRange</span><span class="params">(<span class="keyword">int</span> fromIndex, <span class="keyword">int</span> toIndex)</span> </span>&#123;</span><br><span class="line">    ListIterator&lt;E&gt; it = listIterator(fromIndex);</span><br><span class="line">    <span class="comment">// 从fromIndex的下一个开始，删到toIndex</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i=<span class="number">0</span>, n=toIndex-fromIndex; i&lt;n; i++) &#123;</span><br><span class="line">        it.next();</span><br><span class="line">        it.remove();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="六-abstractlist-重写的方法">六、AbstractList 重写的方法</h2>
<h3 id="1equals">1.equals</h3>
<p><code>equals()</code>方法比较特殊，他是来自于 Collection 和 List 接口中的抽象方法，在 AbstractList 得中实现，但是实际上也是对 Object 中方法的重写。考虑到 <code>equals()</code>情况特殊，所以我们也认为它是一个重写的方法。</p>
<p>我们可以先看看 JavaDoc 是怎么说的：</p>
<blockquote>
<p>比较指定对象与此列表是否相等。当且仅当指定对象也是一个列表，并且两个列表具有相同的大小，并且两个列表中所有对应的元素对相等时，才返回true</p>
</blockquote>
<p>然后再看看源码是什么样的：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">equals</span><span class="params">(Object o)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 是否同一个集合</span></span><br><span class="line">    <span class="keyword">if</span> (o == <span class="keyword">this</span>)</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    <span class="comment">// 是否实现了List接口</span></span><br><span class="line">    <span class="keyword">if</span> (!(o <span class="keyword">instanceof</span> List))</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">	</span><br><span class="line">    <span class="comment">// 获取集合的迭代器并同时遍历</span></span><br><span class="line">    ListIterator&lt;E&gt; e1 = listIterator();</span><br><span class="line">    ListIterator&lt;?&gt; e2 = ((List&lt;?&gt;) o).listIterator();</span><br><span class="line">    <span class="keyword">while</span> (e1.hasNext() &amp;&amp; e2.hasNext()) &#123;</span><br><span class="line">        E o1 = e1.next();</span><br><span class="line">        Object o2 = e2.next();</span><br><span class="line">        <span class="comment">// 两个集合中的元素是否相等</span></span><br><span class="line">        <span class="keyword">if</span> (!(o1==<span class="keyword">null</span> ? o2==<span class="keyword">null</span> : o1.equals(o2)))</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 是否两个集合长度相同</span></span><br><span class="line">    <span class="keyword">return</span> !(e1.hasNext() || e2.hasNext());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>从源码也可以看出，AbstractList 的 <code>equals()</code> 是要求两个集合绝对相等的：顺序相等，并且相同位置的元素也要相等。</p>
<h3 id="2hashcode">2.hashCode</h3>
<p><code>hashCode()</code> 和 <code>equals()</code>情况相同。AbstractList 重新定义了 <code>hashCode()</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">hashCode</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> hashCode = <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">for</span> (E e : <span class="keyword">this</span>)</span><br><span class="line">        hashCode = <span class="number">31</span>*hashCode + (e==<span class="keyword">null</span> ? <span class="number">0</span> : e.hashCode());</span><br><span class="line">    <span class="keyword">return</span> hashCode;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>新的计算方式会获取集合中每一个元素的 hashCode 去计算集合的 hashCode，这可能是考虑到原本情况下，同一个集合哪怕装入的元素不同也会获得相同的 hashCode，可能会引起不必要的麻烦，因此重写了次方法。</p>
<p>我们可以写个测试看看：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">List&lt;String&gt; list1 = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">list1.add(<span class="string">&quot;a&quot;</span>);</span><br><span class="line">System.out.println(list1.hashCode()); <span class="comment">// 128</span></span><br><span class="line">list1.add(<span class="string">&quot;c&quot;</span>);</span><br><span class="line">System.out.println(list1.hashCode()); <span class="comment">// 4067</span></span><br></pre></td></tr></table></figure>
<h2 id="七-总结">七、总结</h2>
<p><strong>List</strong></p>
<p>List 接口继承了 Collection 接口，新增方法的特点主要体现在可以通过下标去操作节点，可以说大部分下标可以作为参数的方法都是 List 中添加的方法。</p>
<p><strong>AbstractList</strong></p>
<p>AbstractList 是实现了 List 的抽象类，他实现了 List 接口中的大部分方法，同时他继承了 AbstractCollection ，沿用了一些 AbstractCollection 中的实现。这两个抽象类可以看成是模板方法模式的一种体现。</p>
<p>他提供了下标版的 <code>add()</code>，<code>remove()</code>，<code>set()</code>的空实现。</p>
<p><strong>迭代器</strong></p>
<p>AbstractList 内部提供两个迭代器，Itr 和 ListItr，Itr 实现了 <code>Iterator</code>接口，实现了基本的迭代删除，而 ListItr 实现了<code>ListIterator</code>，在前者的基础上增加了迭代中添加修改，以及反向迭代的相关方法，并且可以从指定的位置开始创建迭代器。</p>
<p><strong>视图集合SubList</strong></p>
<p>AbstractList 的 SubList 可以看成 AbstractList 的包装类，他在实例化的时候会把外部类实例的引用赋值给成员变量，同名的操作方法还仍然是调用 AbstractList 的，但是基于下标的调用会在默认参数的基础上加上步长，以实现对“视图”的操作，这是适配器模式思想的一种体现。</p>
<p><strong>并发修改检查机制fast-fail</strong></p>
<p>AbstractList 引入了并发修改下 fast-fail 的机制，在内部维护一个成员变量 <code>modelCount</code>，默认为零，每次结构性修改都会让其+1。在迭代过程中会默认检查 <code>modelCount</code>是否符合预期值，否则抛出异常。值得注意的是，这个需要实现类的配合，在实现 <code>add()</code>等方法的时候要让 <code>modelCount</code>+1。对于一些实现类，在迭代中删除可能会抛出 <code>ConcurrentModificationExceptions</code>，就是这方面的问题。</p>
<p>AbstractList 重写了 <code>hashCode()</code>方法，不再直接获取实例的 HashCode 值，而遍历集合，根据每一个元素的 HashCode 计算集合的 HashCode，这样保证了内容不同的相同集合不会得到相同的 HashCode。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag"># java</a>
          
            <a href="/tags/java%E9%9B%86%E5%90%88%E5%AE%B9%E5%99%A8/" rel="tag"># java集合容器</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/11/25/java/%E9%9B%86%E5%90%88%E7%B1%BB%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/java%E9%9B%86%E5%90%88%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90%EF%BC%88%E4%B8%80%EF%BC%89%EF%BC%9ACollection%E4%B8%8EAbstractCollection/" rel="next" title="java集合源码分析（一）：Collection 与 AbstractCollection">
                <i class="fa fa-chevron-left"></i> java集合源码分析（一）：Collection 与 AbstractCollection
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/12/02/java/%E9%9B%86%E5%90%88%E7%B1%BB%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/java%E9%9B%86%E5%90%88%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90%EF%BC%88%E4%B8%89%EF%BC%89%EF%BC%9AArrayList/" rel="prev" title="java集合源码分析（三）：ArrayList">
                java集合源码分析（三）：ArrayList <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/Createsequence.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%7C%7Carchive">
              
                  <span class="site-state-item-count">89</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">21</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%A6%82%E8%BF%B0"><span class="nav-text">概述</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%80-list-%E6%8E%A5%E5%8F%A3"><span class="nav-text">一、List 接口</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1%E6%96%B0%E5%A2%9E%E7%9A%84%E6%96%B9%E6%B3%95"><span class="nav-text">1.新增的方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2%E5%90%8C%E5%90%8D%E7%9A%84%E6%96%B0%E6%96%B9%E6%B3%95"><span class="nav-text">2.同名的新方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3%E9%87%8D%E5%86%99%E7%9A%84%E6%96%B9%E6%B3%95"><span class="nav-text">3.重写的方法</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%8C-abstractlist-%E6%8A%BD%E8%B1%A1%E7%B1%BB"><span class="nav-text">二、AbstractList 抽象类</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1%E4%B8%8D%E6%94%AF%E6%8C%81%E7%9A%84%E5%AE%9E%E7%8E%B0%E4%B8%8E%E6%8A%BD%E8%B1%A1%E6%96%B9%E6%B3%95"><span class="nav-text">1.不支持的实现与抽象方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2%E5%86%85%E9%83%A8%E7%B1%BB%E4%BB%AC"><span class="nav-text">2.内部类们</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%89-sublist%E6%96%B9%E6%B3%95%E4%B8%8E%E5%86%85%E9%83%A8%E7%B1%BB"><span class="nav-text">三、subList方法与内部类</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1sublist-%E5%86%85%E9%83%A8%E7%B1%BB"><span class="nav-text">1.SubList 内部类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2randomaccesssublist-%E5%86%85%E9%83%A8%E7%B1%BB"><span class="nav-text">2.RandomAccessSubList 内部类</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%9B%9B-iterator%E6%96%B9%E6%B3%95%E4%B8%8E%E5%86%85%E9%83%A8%E7%B1%BB"><span class="nav-text">四、iterator方法与内部类</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1%E8%BF%AD%E4%BB%A3%E5%99%A8%E7%9A%84-fast-fail-%E6%9C%BA%E5%88%B6"><span class="nav-text">1.迭代器的 fast-fail 机制</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2itr-%E8%BF%AD%E4%BB%A3%E5%99%A8"><span class="nav-text">2.Itr 迭代器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2listitr-%E8%BF%AD%E4%BB%A3%E5%99%A8"><span class="nav-text">2.ListItr 迭代器</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%94-abstractlist-%E5%AE%9E%E7%8E%B0%E7%9A%84%E6%96%B9%E6%B3%95"><span class="nav-text">五、AbstractList 实现的方法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1add"><span class="nav-text">1.add</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2indexoflastindexof"><span class="nav-text">2.indexOf&#x2F;LastIndexOf</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3addall"><span class="nav-text">3.addAll</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4removerange"><span class="nav-text">4.removeRange</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%85%AD-abstractlist-%E9%87%8D%E5%86%99%E7%9A%84%E6%96%B9%E6%B3%95"><span class="nav-text">六、AbstractList 重写的方法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1equals"><span class="nav-text">1.equals</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2hashcode"><span class="nav-text">2.hashCode</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%83-%E6%80%BB%E7%BB%93"><span class="nav-text">七、总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Createsequence</span>

  
</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  


  <!-- 引入目录截取js -->
  <script type="text/javascript" src="/js/src/custom/custom.js"></script>
</body>
</html>
